/** 
 *  OLMAP 方法函数
 *  map操作方法 
 *  @author Goog2023
 */
import { fCommon, fCustomEvents } from ".";
import { DEFAULTEVENTNAMES } from '../constants';

// 创建ol的map 只能在加载完成js文件之后执行！
function fCreateOLMAP(configs = {}, initCallback, loadedCallback) {
	const options = configs.ol.options;
	const defaultOptions = {
		map: {
			layers: [],
			target: 'map'
		},
		view: {
			projection: configs.proj || 'EPSG:4326',
			center: [103.993166, 30.754256],
			zoom: 10
		}
	};
	const ol = globalThis['ol'];
	const map = new ol.Map({
		view: new ol.View(
			Object.assign(defaultOptions.view, options.view || {})
		),
		...Object.assign(defaultOptions.map, options.map || {})
	});
	//地图初始化完成执行
	fCommon.isFun(initCallback) && initCallback(map);

	// 一些常用事件监听

	// 地图加载完成执行
	fCommon.isFun(loadedCallback) && map.on('onload', () => {
		loadedCallback();
		fCustomEvents.fMapLoadedDispatchEvent();
	});
	// 地图被单击
	map.on('click', (event) => fCustomEvents.fMapClickDispatchEvent(event));
	// 地图被双击
	map.on('dbclick', (event) => fCustomEvents.fMapDbClickDispatchEvent(event))
}

// 在map上根据像素点获取feature 获取后附加到event上面
function fForEachFeatureAtPixel(clickEvent) {
	clickEvent['details'] = []
	clickEvent.map.forEachFeatureAtPixel(clickEvent.pixel, function (feature) {
		clickEvent['details'].push({ feature, coordinate: clickEvent.map.getCoordinateFromPixel(clickEvent.pixel) }); 
	});
}

// 添加图层
function fAddLayer(layer){
	this.addLayer(layer);
}

export {
	fCreateOLMAP,
	fForEachFeatureAtPixel,
	fAddLayer
}